﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace GrindZonesRandomizer
{
    public class Zone
    {
        [XmlElement("Difficulty")]
        public Enums.Difficulties ZoneDifficulty { get; set; }

        [XmlElement("Name")]
        public string ZoneName { get; set; }

        [XmlElement("ID")]
        public string ZoneID { get; set; }

        [XmlElement("AreaLevel")]
        public int ZoneLevel { get; set; }

        public Zone() { }

        public Zone(Enums.Difficulties zD, string zN, string zID, int zL)
        {
            ZoneDifficulty = zD;
            ZoneName = zN;
            ZoneID = zID;
            ZoneLevel = zL;
        }
    }

    [Serializable]
    public class Zones : List<Zone>
    {
        public void SaveZones(string path)
        {
            // Handling Namespaces
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            var xs = new XmlSerializer(typeof(Zones));
            using (var sw = new StreamWriter(path))
            {
                xs.Serialize(sw, this, ns);
                GrindZonesRandomizer.MyLogger.Log("List saved successfully");
            }
        }

        public void LoadZones(string path)
        {
            var xs = new XmlSerializer(typeof(Zones));
            using (var rd = new StreamReader(path))
            {
                var myGZones = (Zones)xs.Deserialize(rd);

                // Reset the List before getting new
                Helpers.MyZones.Clear();
                Helpers.MyZones = myGZones;

                GrindZonesRandomizer.MyLogger.Log("Zones loaded successfully");
                GrindZonesRandomizer.MyLogger.Log("Zones to Grind :");
                foreach (var zone in Helpers.MyZones)
                {
                    GrindZonesRandomizer.MyLogger.Log(String.Format("Name : {0} / Complete Zone ID : {1}_{2} (Zone Level : {3})", zone.ZoneName, (int)zone.ZoneDifficulty, zone.ZoneID, zone.ZoneLevel));
                }
            }
        }

        /// <summary>
        /// Shuffle the List to make it more "random"
        /// </summary>
        /// <typeparam name="T"></typeparam>">
        /// <param name="list"></param>
        public static void Shuffle<T>(IList<T> list)
        {
            var rng = new Random();
            int n = list.Count;
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }

}